import sys

from PyQt5 import QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QStackedWidget, QPushButton
from qfluentwidgets import InfoBar, InfoBarPosition


# --- 1. 导入所有UI类 ---
from Page.LoginPage import LoginPage
from Page.RegisterPage import RegisterPage
from Page.UserPage import UserPage
# --- 定义页面的索引常量 ---
LOGIN_PAGE_INDEX = 0
REGISTER_PAGE_INDEX = 1
USER_PAGE_INDEX = 2
# --- 3. 创建主窗口 ---

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 800, 450)
        self.setWindowIcon(QIcon(':/qfluentwidgets/images/logo.png'))
        self.setWindowTitle('拥抱SpringBoot-项目实例')



        self.stacked_widget = QStackedWidget()
        self.setCentralWidget(self.stacked_widget)

        # 实例化页面
        self.login_page = LoginPage()
        self.register_page = RegisterPage()
        self.user_page = UserPage()

        # 将页面添加到堆栈窗口
        self.stacked_widget.addWidget(self.login_page)
        self.stacked_widget.addWidget(self.register_page)
        self.stacked_widget.addWidget(self.user_page)

        # 连接信号和槽
        self.connect_signals()

        # 设置初始页面
        self.stacked_widget.setCurrentIndex(LOGIN_PAGE_INDEX)


    def connect_signals(self):
        """连接所有按钮的信号到对应的槽函数"""
        # --- 登录页面的信号 ---
        self.login_page.goRegisterButton.clicked.connect(self.go_to_register_page)
        self.login_page.login_success.connect(self.go_to_user_page)
        self.login_page.login_failed.connect(self.show_error_info)

        # --- 注册页面的信号 ---
        self.register_page.goLoginButton.clicked.connect(self.go_to_login_page)

        # --- 用户页面的信号 ---
        self.user_page.exitLogin.clicked.connect(self.handle_logout)

    # --- 页面切换的槽函数 ---
    def go_to_login_page(self):
        self.stacked_widget.setCurrentIndex(LOGIN_PAGE_INDEX)
        self.login_page.account.clear()
        self.login_page.password.clear()

    def go_to_register_page(self):
        self.stacked_widget.setCurrentIndex(REGISTER_PAGE_INDEX)
        self.register_page.name.clear()
        self.register_page.account.clear()
        self.register_page.password.clear()
        self.register_page.password_2.clear()

    def go_to_user_page(self, username):
        self.stacked_widget.setCurrentIndex(USER_PAGE_INDEX)
        self.user_page.handle_up_user()

    def handle_logout(self):
        print("用户已退出登录")
        self.go_to_login_page()

    def show_error_info(self, error_message='未知错误'):
        """显示成功信息"""
        InfoBar.error(
            title='失败',
            content=error_message,
            orient=InfoBarPosition.TOP_LEFT,
            isClosable=True,
            duration=3000,
            parent=self
        )


if __name__ == '__main__':
    # 设置应用程序高DPI缩放支持
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
